package com.jxb.test20241021;

public class TokenBucket {

    private static long tokens;//剩余的令牌数量

    private static long putTokenRate=5;//放令牌的速率,每秒放5个

    private static long bucketSize=50;//桶的大小

    public static void main(String[] args) throws InterruptedException {
        //预热1分钟
        new Thread(new Runnable() {
            @Override
            public void run() {
                schTokens();
            }
        }).start();
        Thread.sleep(1000);

        //模拟并发场景
        while (true) {
            Thread.sleep(100);
            if (!limit()) {
                tokens--;
            }else {
                System.out.println("已限流......");
            }
        }
    }

    //匀速加入令牌到桶中
    public static void schTokens() {
        for (;;) {
            if (tokens+putTokenRate <= bucketSize) {
                tokens=tokens+putTokenRate;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean limit() {
       if (tokens <= 0) {
           //限流
           return true;
       }else {
           return false;
       }
    }

}
